home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8079 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: anvil.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: macro that return value, how?
  5. Date: 29 Feb 1996 14:59:36 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4h5b4oINN8l1@anvil.ugrad.cs.ubc.ca>
  8. References: <3133e87b.868433@news.csus.edu>
  9. NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
  10.  
  11. In article <3133e87b.868433@news.csus.edu>,
  12. Jerry Leong <wleong@sfsu.edu> wrote:
  13. >
  14. >Hi,
  15. >    I need to define a macro that will first calculate a given a
  16. >parameter and then return it. How can I do that?
  17. >
  18. >p/s: Say I pass a value to the macro, macro will perform some
  19. >addition, then return the value.
  20. >
  21. >#define add1(x)  { x+=VAR; return x; }   
  22. >
  23. >something like that by the above does not compile.
  24.  
  25. It's not standard C.  The GCC compiler supports the construct, by the way. It
  26. does this by allowing statement blocks to act as expressions, whose value is
  27. that of the last statement.
  28.  
  29. In standard C, you can do this using comma expressions. In your example, no
  30. comma expression is required, since x+=VAR is an expression-statement, whose
  31. value is that of x+VAR.
  32.  
  33. #define add1(x) ((x) += VAR)
  34.  
  35.  
  36. If you want to do multi-step computation, you use a comma expression, whose
  37. members are guaranteed to evaluate left to right:
  38.  
  39. #define addiv(x) ((x) += VAR1; (x) /= VAR2; (x)++)
  40.  
  41. The result of addiv(v) is the value of v just before it is decremented in the
  42. final step. For instance, if v is initially 3, VAR1 is 1, and VAR2 is 2,
  43. the result of the function is 2, and v is set to 3.
  44. -- 
  45.  
  46.